package jcataloger.renderers;

import java.awt.Component;
import java.io.File;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.filechooser.FileSystemView;

import jcataloger.beans.ImageItem;
import jcataloger.resources.Parameters;
import jcataloger.util.Debug;

/**
 * This class is used to render JList components in the project. It is used for showing <br>
 * images near items in the list according to their types.
 * @author sekobey
 *
 */
public class JCatalogerListRenderer extends JLabel implements ListCellRenderer {
	
	public Component getListCellRendererComponent(JList list, Object value,
			int index, boolean isSelected, boolean cellHasFocus) {

		ClassLoader loader = this.getClass().getClassLoader();
		ImageIcon diskIcon = new ImageIcon(loader.getResource(Parameters.getString("icons22x22.disk")));
		ImageIcon folderIcon = new ImageIcon(loader.getResource(Parameters.getString("icons22x22.folder")));
		ImageIcon fileIcon = new ImageIcon(loader.getResource(Parameters.getString("icons22x22.file")));
		ImageIcon upIcon = new ImageIcon(loader.getResource(Parameters.getString("icons22x22.folderup")));
		
		if ( value instanceof String ) {
			setText( value.toString() );
			setIcon( diskIcon );
		}
		if ( value instanceof ImageItem ) {
			ImageItem item = (ImageItem)value;
			setText( item.getName() );
			Icon icon = null;
			if ( item.isUpDirectory() ) {
				setText( item.getName() );
				icon = upIcon;
			}
			else if ( item.isFile() ) {
				try {
					FileSystemView view = FileSystemView.getFileSystemView();
					String fileName = item.getName();
					String prefix = fileName;
					String suffix = "txt";
					if ( fileName.indexOf(".") > -1 ) {
						prefix = fileName.substring(0, fileName.indexOf("."));
						suffix = fileName.substring(fileName.indexOf("."));
						if (prefix.length() < 4)
							prefix = "temp";
					}
					File tmpFile = File.createTempFile(prefix, suffix);
					icon = view.getSystemIcon( tmpFile );
					tmpFile.delete();
				} catch (Exception e) {
					Debug.println( e.getMessage() );
					e.printStackTrace();
				} finally {
					if ( icon == null )
						icon = fileIcon;
				}
				
			}
			else {
				icon = folderIcon;
			}
			setIcon( icon );
		}
		if (isSelected) {
			setBackground(list.getSelectionBackground());
			setForeground(list.getSelectionForeground());
		}
		else {
			setBackground(list.getBackground());
			setForeground(list.getForeground());
		}
		setEnabled(list.isEnabled());
		setFont(list.getFont());
		setOpaque(true);
		return this;
	}
	
}

	